<?php
class C_Insurance extends Controller {
    private $logger;
    function __construct($template_mod = "general") {
        parent::Controller();
        $this->template_mod = $template_mod;
        $this->logger = LoggerManager::getLogger('local.controllers.C_Insurance');
    }

    public function actionGetInsuranceEditPageAjax($insuranceId = 0) {
        if (isset($_GET['insuranceId'])) {
    	   $insuranceId    =   $_GET['insuranceId'];
        }
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        $this->logger->info("Start action GetInsuranceEditPageAjax {insuranceId='$insuranceId'}");
        $objInsurance   =   Celini::newORDO('Insurance', $insuranceId);
        $patientId      =   $objInsurance->getPatientId();
        $this->assign('insuranceId', $insuranceId);
        $this->assign('patientName', Celini::newORDO('Person', $patientId)->getName());
        //@LOCALIZATION
        $orders =   L10nHelper::getYMDorder();
        $this->assign('datePart_0', $orders[0]);
        $this->assign('datePart_1', $orders[1]);
        $this->assign('datePart_2', $orders[2]);

        // Insurance code
        $insuranceCode  =   $objInsurance->getInsuranceCode();
        $pattern  =   '/^(\w{2})-(\d{1})-(\d{2})-(\d{2})-(\d{3})-(\d{5})$/';
        if (preg_match($pattern, $insuranceCode, $matches)) {
            $this->assign('insuranceCode', $matches);
        }

        // Usage date
        $dateIssued =   $objInsurance->getLocalizedDate('date_issued');
        $dateIssued =   L10nHelper::getDateParts($dateIssued);
        $dateExpired =   $objInsurance->getLocalizedDate('date_expired');
        $dateExpired =   L10nHelper::getDateParts($dateExpired);
        $this->assign('date_issued', $dateIssued);
        $this->assign('date_expired', $dateExpired);
        $this->assign('hospitalName', $objInsurance->getRegisteredHospitalName());
        $this->logger->info("End action GetInsuranceEditPageAjax {insuranceId='$insuranceId'}");
        $result['result']	=	$this->view->render('insurance_edit.html');
        return json_encode($result);
    }

    public function actionGetHospitalAjax(){
        $q = strtolower($_GET['q']);
        if (!$q || strlen($q) < 1) return;
        $names	=	Celini::newORDO('Hospital')->getHospitalsByName($q);
        foreach ($names as $value) {
            echo $value['hospital_id'] . '|' . $value['hospital_name'] . "\n";
        }
    }

    public function actionEditInsuranceAjax() {
        $result = array(
                    'error'     =>  array('code' => CoreErrorCode::NORMAL,
                                          'mess' => ''),
                    'result'    =>  ''
        );
        if (isset($_POST['insuranceId'])) {
            $insurance  =   Celini::newORDO('Insurance', $_POST['insuranceId']);
            $patientId  =   $insurance->getPatientId();
        }
        else {
            $insurance  =   Celini::newORDO('Insurance');
            $patientId  =   $_POST['patientId'];
        }

    	// Insurance code
    	$insCode1  =   Utils::sanitizeText($_POST['insuranceCode_0']);
    	$insCode2  =   Utils::sanitizeText($_POST['insuranceCode_1']);
    	$insCode3  =   Utils::sanitizeText($_POST['insuranceCode_2']);
    	$insCode4  =   Utils::sanitizeText($_POST['insuranceCode_3']);
    	$insCode5  =   Utils::sanitizeText($_POST['insuranceCode_4']);
    	$insCode6  =   Utils::sanitizeText($_POST['insuranceCode_5']);
    	$insuranceCode = $insCode1 . "-" . $insCode2 . "-" . $insCode3 . "-" . $insCode4 . "-" . $insCode5 . "-" . $insCode6;

    	// Usage date
    	$issuedDate['year']    =   (int)Utils::sanitizeText($_POST['issued_yyyy']);
        $issuedDate['month']   =   (int)Utils::sanitizeText($_POST['issued_mm']);
        $issuedDate['day']     =   (int)Utils::sanitizeText($_POST['issued_dd']);
        $issuedDate            =   L10nHelper::getISODate($issuedDate);

        $expiredDate['year']   =   (int)Utils::sanitizeText($_POST['expired_yyyy']);
        $expiredDate['month']  =   (int)Utils::sanitizeText($_POST['expired_mm']);
        $expiredDate['day']    =   (int)Utils::sanitizeText($_POST['expired_dd']);
        $expiredDate           =   L10nHelper::getISODate($expiredDate);

        $correctRoute = (isset($_POST['correctRoute']) && $_POST['correctRoute'] == 'on') ? 1 : 0;
        $paidFor36Month = (isset($_POST['paidFor36Month']) && $_POST['paidFor36Month'] == 'on') ? 1 : 0;
        
        // Check if insurance card has already existed
        if ($insurance->checkExist($patientId, $insuranceCode, $issuedDate, $expiredDate)) {
            $result['error']['code']    =   CoreErrorCode::COMMON_ERROR;
            $result['error']['mess']    =   L10nHelper::_('The insurance card has already existed');
        }
        else {
	        // Hospital
	        $hospitalId   =   Utils::sanitizeAndCaseTitle($_POST['registeredHospitalId']);
	        $insurance->setData($patientId, $insuranceCode, $issuedDate, $expiredDate,
	                   $hospitalId, $correctRoute, $paidFor36Month);
	        $insurance->persist();
        }
        return json_encode($result);
    }

    private function buildInsuranceListOptions($insInfoArray) {
    	$html =   "<option value='' label='- - -'>- - - </option>";
    	foreach ($insInfoArray as $insItem) {
    		$insId        =   $insItem['insurance_id'];
    		$insCode      =   $insItem['insurance_code'];
    		$dateIssued   =   $insItem['date_issued'];
    		$dateExpired  =   $insItem['date_expired'];
    		$hospitalName =   $insItem['hospital_name'];
    		$insName      =   $insCode . "   " . $dateIssued . "-" . $dateExpired;
            $html    .=   "<option label='$insName' value='$insId' insurance_code='$insCode' date_issued='$dateIssued' date_expired='$dateExpired' hospital_name='$hospitalName'>$insName</option>";
    	}
    	return $html;
    }

}
?>